/*
 * Copyright (c) 2021. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.kason.heat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @author 卢清波
 * @date 2021/1/25 13:01
 */
public class HeatServerHandler extends ChannelInboundHandlerAdapter
{
    /**
     * 读取客户端发送的数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("服务端读取线程："+Thread.currentThread().getName());
        String s = msg.toString();
        System.out.println("读取客户端数据："+s);
        // ctx.fireChannelRead(msg);
    }

    /**
     * 读取完毕
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

        // ctx.writeAndFlush("你好客户端，我是服务端"+Thread.currentThread().getName());
        // ctx.fireChannelReadComplete();
    }

    /**
     * 处理异常
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        // ctx.fireExceptionCaught(cause);
    }
    int read = 0 ;
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent event = (IdleStateEvent) evt;
        IdleState state = event.state();

        switch (state){
            case READER_IDLE:
                read++;
                System.out.println("读事件空闲！");
            case WRITER_IDLE:
                System.out.println("写事件空闲！");
            default:
                ;
            break;
        }

        if(read>=3)
        {
            System.out.println(ctx.channel().remoteAddress()+":超过3次，关闭客户端连接，发送idle close");
            ctx.writeAndFlush("idle close");
            ctx.channel().close();
        }


    }




}
